<?php

class DefaultController extends Controller
{

	public $aCategories = array();
	public $aFilters = array();

	public function actionIndex($category_id = null)
	{
		$this->layout='//layouts/main-left';
		$toView = array();
        $toView['sortBy'] = $this->_getParam('s', 'newest');

		$oPages = new Pages();
        $oGoods = new Goods();
        $oCategories = new Categories();
        $oPhotos = new Photos();

        $oCategory = $oCategories->onlyPublic()->findByAttributes(array(
//                                                                       'id' => $category_id
                                                                       'alias' => $category_id
                                                                  ));

		$toView['oCategory'] = $oCategory;

		if(!$oCategory)
			throw new CHttpException(404,'The specified post cannot be found.');

		$toView['categoryId'] = $categoryId = $oCategory->id;

		// Breadcrumbs
		$oCategories = new Categories();
		$aCategories = $oCategories->getAllParents($oCategory->id);
		$aCategories[$oCategory->id] = $oCategory->id;

		$this->_selectBreadcrumbs($aCategories);

		$aCategories[$categoryId] = $categoryId;


		$this->aFilters = $this->_getParams();
		if($categoryId > 0)
			$this->aFilters['category_id'] = $categoryId;

		$oPage = $oPages->findByAttributes(
			array(),
			'category_id iN('. implode(', ', $aCategories) .') AND type = :type',
			array(':type' => 'page')
		);

		if(!empty($oPage))
		{
			$oGallery = new Gallery();

			$toView['oPageRow'] = $oPage;
			$toView['oGalleryRow'] = $oGallery->findByAttributes(array(
			                                                       'category_id' => $oCategory['id']
			                                                  ));
			$oPhotos->selectByRow($toView['oGalleryRow']);
		}

        $this->selectCategories = array($categoryId => $categoryId);

		$categoriesIds = $oCategories->getAllChild($categoryId);
		if(count($categoriesIds) > 0)
		{
			$oRowset = $oCategories->findAllByAttributes(array('relative_id' => $categoryId));
			$oPhotos->selectMainByRowset($oRowset);

			$toView['oRowset'] = $oRowset;

			return $this->render('categories', $toView);
		}

        if(!isset($this->aFilters['s']))
            $this->aFilters['s'] = 'newest';

        $this->oPager->setPageSize(51);

		$categoriesIds[$categoryId] = $categoryId;
        $oRowset = $oGoods->getList($categoriesIds, $this->oPager, $this->aFilters);
//        $oRowset = $oGoods->status(array(1,2))->getList($categoriesIds, $this->oPager, $this->aFilters);
//        $oRowset = $oGoods->getList($categoriesIds, $this->oPager);
        $oPhotos->selectMainByRowset($oRowset);

		$this->aCategories = $toView['aCategories'] = $aCategories;
		$toView['oRowset'] = $oRowset;


		// Select titles
		$this->_selectTitlesForList($oCategory);

		$this->render('index', $toView);
	}

	protected function _selectTitlesForList($oCategory)
	{
		$oCategories = new Categories();
		$oTitleCategories = $oCategories->limit(4)->findAllByAttributes(array(),
			'relative_id = :relative_id AND id != :id', array(
				':relative_id' => $oCategory->relative_id,
				':id' => $oCategory->id,
			)
		);

		$title = '';
		foreach($oTitleCategories as $aCat)
		{
			if($title != '')
				$title .= ', ';
			$title .= $aCat->title;
		}

		$title = $oCategory->title .', '. $title;
		$ogTitle = $title;

		$title = 'Купить '. $title .'. Бесплатная доставка. Американские, оригинальные.';
		$description = !empty($oCategory->meta_description) ? $oCategory->meta_description : 'Купить по телефону '. Yii::app()->params['phone'] .', '. $ogTitle .', оригинальные товары из америки. Бесплатная доставка. Возврат 365 дней.';
		$this->addTitle($title)
			->addKeywords(!empty($oCategory->meta_keywords) ? $oCategory->meta_keywords : $title)
			->addDescription($description);

		$this->setOg(array(
			'title' => $ogTitle,
			'image' => null,
			'description' => String::substr(String::stripTagsAttributes($oCategory->description), 250),
		));
	}

	protected function _selectBreadcrumbs($aCategories)
	{
		if($aCategories)
		{
			$oCategories = new Categories();
			$oCategories = $oCategories->onlyPublic()->id($aCategories)->findAllByAttributes(
				array(),
				'relative_id != :relative_id',
				array(':relative_id' => 0)
			);

			if($oCategories)
				foreach($oCategories as $oCategory)
					$this->breadcrumbs[$oCategory->title] = Yii::app()->createUrl('goods/default/index', array('category_id' => $oCategory->createUrlId()));
		}
	}

    public function actionView($id)
	{
//		echo 'view'; exit;
		$toView = array();
	    $oPages = new Pages();
	    $oGoods = new Goods();
	    $oVideo = new Video();
	    $oPhotos = new Photos();
		$oGoodsView = new GoodsView();

		if($this->_getParam('goods_id') > 0)
			$oRow = $oGoods->findByAttributes(array('id' => $this->_getParam('goods_id')));
		else
			$oRow = $oGoods->findByAttributes(array('alias' => $id));
//print_r($oRow);
        if(!$oRow)
            throw new CHttpException(404,'The specified post cannot be found.');

        $oPhotosRowset = $oPhotos->selectByRow($oRow);
	    $oVideo->selectByRow($oRow);

		// Set count view
	    if((!Yii::app()->request->cookies->contains('_gv_') || Yii::app()->request->cookies['_gv_']->value != $oRow->id) && $oRow->id > 0 )
		{
			Yii::app()->request->cookies['_gv_'] = new CHttpCookie('_gv_', $oRow->id, array(
			                                                                         'httpOnly' => true,
			                                                                         'expire' => time() + 86400,
			                                                                         'path' => $_SERVER['REQUEST_URI']
			                                                                    ));

			$oGoodsView->setAttributes(array(
			                                'goods_id' => $oRow->id,
			                                'before_view_id' => (
				                                    Yii::app()->request->cookies->contains('_bv_') && Yii::app()->request->cookies['_bv_']->value != $oRow->id ?
					                                Yii::app()->request->cookies['_bv_']->value : null
				                                ),
			                                'time' => time(),
			                                'ip' => (!empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''),
			                           ));
			$oGoodsView->save();
		}

	    // Before view
	    Yii::app()->request->cookies['_bv_'] = new CHttpCookie('_bv_', $oRow->id, array(
	                                                                             'httpOnly' => true,
	                                                                             'expire' => time() + 86400,
	                                                                             'path' => '/'
	                                                                        ));

		$oCategories = new Categories();
		$this->selectCategories = $oCategories->getAllParents($oRow->category_id);
		$this->selectCategories[$oRow->category_id] = $oRow->category_id;
		if($this->selectCategories)
		{
			$oCategories = $oCategories->id($this->selectCategories)->findAllByAttributes(
				array(), 
				'relative_id != :relative_id', 
				array(':relative_id' => 0)
			);

			if($oCategories)
				foreach($oCategories as $oCategory)
					$this->breadcrumbs[$oCategory->title] = Yii::app()->createUrl('goods/default/index', array('category_id' => $oCategory->createUrlId()));
		}

		$toView['aColors'] = $oGoods->getAllColors($oRow);

		// Sizes
		$oGoodsProperty = new GoodsProperty();
		$toView['aSizes'] = $oGoodsProperty->getByType($oRow->id, '3');
	    $oGoodsProperty->selectByRowset($toView['aColors'], '3');

		// Color
		$oGoodsProperty = new GoodsProperty();
		$oGoodsProperty->selectByRowset($toView['aColors'], '4');

	    // Select viewed other
		$relatedIds = $oGoodsView->getViewedGoodsId($oRow->id);
//	    print_r($relatedIds); exit;
		if($relatedIds)
		{
			$toView['oRelated'] = $oGoods->limit(5)->orderByRand()->id($relatedIds)->findAll();
			$oPhotos->selectMainByRowset($toView['oRelated']);
		}

		$toView['oRow'] = $oRow;


	    // select size page
	    $oPage = $oPages->findByAttributes(
		    array(),
		    'category_id iN('. implode(', ', $this->selectCategories) .') AND type = :type',
		    array(':type' => 'size')
	    );
//	    print_r($oPage);
	    $toView['oPageSize'] = $oPage;

	    if($this->_isXmlHttpRequest())
	    {
            $this->layout='//layouts/empty';
	    }
	    else
	    {
	        $title = 'Купить '. $oRow->title .', оригинальные товары из америки - отзывы, видео, цена';
	        $description = !empty($oRow->meta_description) ? $oRow->meta_description : 'Купить по телефону '. Yii::app()->params['phone'] .', '. $oRow->title .', оригинальные товары из америки. Бесплатная доставка.';
		    $this->addTitle($title)
			     ->addKeywords(!empty($oRow->meta_keywords) ? $oRow->meta_keywords : $title)
		         ->addDescription($description);

		    $photoUrl = '';
		    if(!empty($oPhotosRowset))
		    {
			    $oPhoto = current($oPhotosRowset);
			    if(!empty($oPhoto))
			        $photoUrl = $oPhoto->path . $oPhoto->file;
		    }

		    $this->setOg(array(
			    'title' => $oRow->title,
			    'image' => $photoUrl,
			    'description' => String::substr(String::stripTagsAttributes($oRow->description), 250),
		    ));

            $this->layout='//layouts/main';
	    }

		$this->render('view', $toView);
	}

	public function actionQuantitycheck()
	{
		if(!$this->_getParam('goods_id'))
			exit;

		$toView = array();
		$oRow = new Goods();
		$oPhotos = new Photos();
		$oGoodsView = new GoodsView();

		$oRow = $oRow->findByPk($this->_getParam('goods_id'));

		$oParser = new Parser();
		$oParser = $oParser->findByPk($oRow['parser_id']);

		if(!$oParser)
			return $this->_renderWindowEmptySize($oRow->id);

//		echo $oGoods['original_url'];

		$oGrabber = new Grabber();
		$aPriceRow = $oGrabber->getRow($oParser->class, $oRow['original_url']);

//		print_r($oPriceRow); exit;

		if(!$aPriceRow)
		{
			$oRow->status = 0;
			$oRow->save();

			return $this->_renderWindowEmptySize($oRow->id);
		}

//		print_r($aPriceRow); exit;

		if($aPriceRow && !empty($aPriceRow['price']))
		{
			$oRow->old_price = 0;
			if($oRow->price > $aPriceRow['price'])
				$oRow->old_price = $oRow->price;

			$oRow->price = $aPriceRow['price'];
			if(!empty($aPriceRow['msrp']))
				$oRow->msrp = $aPriceRow['msrp'];

			$oRow->save();
		}

		if(isset($aPriceRow['sizes']))// && isset($aPriceRow['sizes'][$this->_getParam('stock_value_id')]))
		{
			$oGoodsProperty = new GoodsProperty();
			$oValues = $oGoodsProperty->getListByStoreId(array_keys($aPriceRow['sizes']), $oRow->id);

			if(empty($oValues))
				return $this->_renderWindowEmptySize($oRow->id);

			$response = array(
				'success' => true
			);

			foreach($oValues as $oValue)
			{
				if(!empty($aPriceRow['sizes'][$oValue->stock_value_id]))
				{
					$oValue->count = $aPriceRow['sizes'][$oValue->stock_value_id];
					$oValue->save();

					$response['counts'][$oValue->value_id] = $oValue->count;
				}
			}

			echo json_encode($response); exit;
		}

		return $this->_renderWindowEmptySize($oRow->id);
	}

	protected function _renderWindowEmptySize($id)
	{
		$toView = array();
		$oGoods = new Goods();
		$oPhotos = new Photos();
		$oGoodsView = new GoodsView();

		$relatedIds = $oGoodsView->getViewedGoodsId($id, 30);
		if($relatedIds)
		{
			$toView['oRelated'] = $oGoods->status(array(1, 2))->limit(3)->orderByRand()->id($relatedIds)->findAll();
			$oPhotos->selectMainByRowset($toView['oRelated']);
		}

		$this->layout='//layouts/empty';

		return $this->render('quantitycheck', $toView);
	}

}